package com.sig.util;

import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 线程工厂工具
 *
 * @author sig
 * @since 2019/1/26
 */
public final class ThreadFactoryUtil {

    private ThreadFactoryUtil() {
    }

    public static ThreadFactory getThreadFactory(final String namePrefix) {
        return new ScheduleThreadFactory(namePrefix);
    }

    private static class ScheduleThreadFactory implements ThreadFactory {
        final ThreadGroup group;
        final AtomicInteger threadNumber = new AtomicInteger(1);
        final String namePrefix;

        public ScheduleThreadFactory(final String namePrefix) {
            final SecurityManager securityManager = System.getSecurityManager();
            group = securityManager != null ? securityManager.getThreadGroup() : Thread.currentThread().getThreadGroup();
            this.namePrefix = namePrefix;
        }

        @Override
        public Thread newThread(final Runnable r) {
            final Thread thread = new Thread(group, r, namePrefix + threadNumber.getAndIncrement());
            if (thread.isDaemon())
                thread.setDaemon(false);
            if (thread.getPriority() != Thread.NORM_PRIORITY)
                thread.setPriority(Thread.NORM_PRIORITY);
            return thread;
        }
    }
}
